package com.roc.web.action.freeze;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.roc.bean.FreezeBean;
import com.roc.bean.FreezeListBean;
import com.roc.newPage.IPageService;
import com.roc.page.BaseSearchCondition;
import com.roc.page.PaginationBaseAction;
import com.roc.pojo.Operators;
import com.roc.service.IExcelService;
import com.roc.service.ServiceException;
import com.roc.service.freeze.IFreezeService;
import com.roc.util.Constance;
import com.roc.util.constant.Constant;
import com.roc.util.constant.Role;
import com.roc.web.action.terminal.TerminalStatisticsSearchCondition;

@Component
@Namespace("/freeze")
@SuppressWarnings("all")
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class QueryFreezingMerchantAction extends PaginationBaseAction {
	private static Logger logger = Logger.getLogger(QueryFreezingMerchantAction.class);
	private InputStream excelFile;
	private FreezingMerchantSearchCondition searchCondition;
	private FreezeBean freezeBean;
	private String keyStr;
	private List<FreezeListBean> freezeList = new ArrayList<FreezeListBean>();
	private File file;
	protected List<Object> syslogList=new ArrayList<Object>();//操作记录列表
	private String exportFlag;
	@Autowired
	IPageService pagenitionService;
	@Autowired
	IFreezeService freezeService;
	@Autowired
	private IExcelService excelService;

	/**
	 * 初始化冻结商户页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "init", results = {
			@Result(name = "success", location = "/pages/freeze/freezeMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String init() throws Exception {
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		if (op.getRoleType().equals(Role.CLEAR_OPERATORS.getCode())
				|| op.getRoleType().equals(Role.CLEAR_LEAD.getCode())
				|| op.getRoleType().equals(Role.SYSTEM.getCode())
				|| op.getRoleType().equals(Role.RISK_CONTROL_LEAD.getCode())
				|| op.getRoleType().equals(
						Role.RISK_CONTROL_OPERATORS.getCode())) {
			return SUCCESS;
		}
		addActionError("无权限访问!!!");
		return ERROR;
	}

	/**
	 * 查询冻结商户页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "queryFreeze", results = {
			@Result(name = "success", location = "/pages/freeze/freezeMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String queryFreeze() throws Exception {
		try {
			if (searchCondition == null) {
				searchCondition = (FreezingMerchantSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new FreezingMerchantSearchCondition();
				}
			}
			int rows = pagenitionService.countSQL(searchCondition);

			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), Constance.PAGE_MAX_SIZE);
				dealWithTheListSpecially(searchRsList);

				List<FreezeBean> list = new ArrayList<FreezeBean>();
				if (null != searchRsList && searchRsList.size() > 0) {
					Iterator<?> iterator = searchRsList.iterator();
					while (iterator.hasNext()) {
						Object[] obj = (Object[]) iterator.next();

						DecimalFormat df = new DecimalFormat("#.##");// 数据库存的分，转成元保留小数点后两位
						double freezeAmt = Double.parseDouble(Constance
								.Null2EmptyTrim(obj[2]));
						double freezeHadSum = Double.parseDouble(Constance
								.Null2EmptyTrim(obj[3]));
						double freezeWeiSum = Double.parseDouble(Constance
								.Null2EmptyTrim(obj[4]));

						FreezeBean fb = new FreezeBean();
						fb.setKeyStr(Long.parseLong(Constance
								.Null2EmptyTrim(obj[0])));
						fb.setMchntCd(Constance.Null2EmptyTrim(obj[1]));
						fb.setFreezeAmt((df.format(freezeAmt / 100)).toString());
						fb.setFreezeHadSum((df.format(freezeHadSum / 100))
								.toString());
						fb.setFreezeWeiSum((df.format(freezeWeiSum / 100))
								.toString());
						fb.setUseStatus(Constance.Null2EmptyTrim(obj[5]));
						fb.setFreezeFlag(Constance.Null2EmptyTrim(obj[6]));
						fb.setOldTransKey(Constance.Null2EmptyTrim(obj[7]));
						fb.setOldTransCardNo(Constance.Null2EmptyTrim(obj[8]));
						fb.setRecCrtTs(Constance.Null2EmptyTrim(obj[9]));
						fb.setRecUpdTs(Constance.Null2EmptyTrim(obj[10]));
						fb.setRemark(Constance.Null2EmptyTrim(obj[11]));
						fb.setOperator(Constance.Null2EmptyTrim(obj[12]));
						fb.setMchtName(Constance.Null2EmptyTrim(obj[13]));
						fb.setBranchCompy(Constance.Null2EmptyTrim(obj[14]));
						fb.setOneAgent(Constance.Null2EmptyTrim(obj[15]));
						fb.setDirectAgent(Constance.Null2EmptyTrim(obj[16]));
						list.add(fb);
					}
					searchRsList.clear();
					searchRsList.addAll(list);

				}

			}
			if (searchRsList.size() == 0) {
				getRequest().setAttribute("msge", "查询冻结商户为空");
			}

			this.setTotalPage(this.calcuTotalPage(rows));
			getRequest().setAttribute(SEARCH_RS_LIST, searchRsList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			setSearchToConditionSession(searchCondition);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());
			return ERROR;
		}
		return SUCCESS;

	}

	/**
	 * 商户冻结流水和冻结操作记录显示
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "freezeDetail", results = {
			@Result(name = "success", location = "/pages/freeze/freezeDetail.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String freezeDetail() throws Exception {
		try {
			freezeList = freezeService.findByKey(keyStr);
            syslogList = freezeService.findSyslogByKey(keyStr);
			getRequest().setAttribute("freezeList", freezeList);
			getRequest().setAttribute("syslogList", syslogList);
			getRequest().setAttribute(CURRENT_PAGE, this.getCurrentPage());
			getRequest().setAttribute(TOTAOL_PAGE, this.getTotalPage());
			if (freezeList.size() == 0) {
				getRequest().setAttribute("msg", "查询该商户冻结流水为空");
			}
			if (syslogList.size() == 0) {
				getRequest().setAttribute("msg1", "查询该商户冻结操作记录为空");
			}
		} catch (Exception e) {
			addActionError("商户冻结流水或操作记录显示失败~");
			e.printStackTrace();

		}

		return SUCCESS;

	}

	/**
	 * 初始化添加冻结商户
	 * 
	 * @return
	 */
	@Action(value = "addFreezeMerInit", results = {
			@Result(name = "success", location = "/pages/freeze/addRegisterMerinfo.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String addFreezeMerInitView() {
		logger.info("初始化添加页面~");
		return SUCCESS;
	}

	/**
	 * 添加冻结商户
	 * 
	 * @return
	 */
	@Action(value = "addFreezeMer", results = {
			@Result(name = "success", location = "/pages/freeze/freezeMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String addFreezeMerView() {
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		try {
			int count = freezeService.addFreezeMerInfo(freezeBean, op);
			if (count > 0) {
				addActionMessage("添加成功~");
			}
		} catch (ServiceException e) {
			addActionError("添加冻结商户失败~");
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 初始化修改页面
	 * 
	 * @return
	 */
	@Action(value = "updateFreezeMerInit", results = {
			@Result(name = "success", location = "/pages/freeze/addRegisterMerinfo.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String updateFreezeMerViewInit() {
		try {
			freezeBean = freezeService.findMerInfo(freezeBean);
			getRequest().setAttribute("flag", "update");
		} catch (ServiceException e) {
			addActionError("查询冻结商户失败~");
			e.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 修改冻结商户
	 * 
	 * @return
	 */
	@Action(value = "updateFreezeMer", results = {
			@Result(name = "success", location = "/pages/freeze/freezeMana.jsp"),
			@Result(name = "error", location = "/error.jsp") })
	public String updateFreezeMerView() {
		Operators op = (Operators) getSession().getAttribute(
				Constant.SESSION_LOGIN_MERCHANT);
		try {
			int count = freezeService.updateFreezeMerInfo(freezeBean, op);
			if (count > 0) {
				addActionMessage("修改成功~");
			}
		} catch (ServiceException e) {
			addActionError("修改冻结商户失败~");
			e.printStackTrace();
		}
		return SUCCESS;
	}

	@Action(value = "exportInit", results = {
			@Result(name = "success", type = "stream", params = {
					"contentType", "application/vnd.ms-excel", "inputName",
					"excelFile", "contentDisposition",
					"attachment;filename=${excelName}.xlsx", "bufferSize",
					"1024*3" }),
			@Result(name = "error", location = "/error.jsp") })
	public String exportFreezeMcht() throws Exception {

		try {
			if (searchCondition == null) {
				searchCondition = (FreezingMerchantSearchCondition) getSearchConditionFromSession();
				if (searchCondition == null) {
					searchCondition = new FreezingMerchantSearchCondition();
				}
			}
			// org();//加载分公司
			int rows = pagenitionService.countSQL(searchCondition);
			if (rows > 0) {
				searchRsList = pagenitionService.findAllSQL(searchCondition,
						calcuStart(getCurrentPage()), rows);
			}
			List<FreezeBean> list = new ArrayList<FreezeBean>();
			if (null != searchRsList && searchRsList.size() > 0) {
				Iterator<Object> iterator = searchRsList.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();

					DecimalFormat df = new DecimalFormat("#.##");// 数据库存的分，转成元保留小数点后两位
					double freezeAmt = Double.parseDouble(Constance
							.Null2EmptyTrim(obj[2]));
					double freezeHadSum = Double.parseDouble(Constance
							.Null2EmptyTrim(obj[3]));
					double freezeWeiSum = Double.parseDouble(Constance
							.Null2EmptyTrim(obj[4]));

					FreezeBean fb = new FreezeBean();
					fb.setKeyStr(Long.parseLong(Constance
							.Null2EmptyTrim(obj[0])));
					fb.setMchntCd(Constance.Null2EmptyTrim(obj[1]));
					fb.setFreezeAmt((df.format(freezeAmt / 100)).toString());
					fb.setFreezeHadSum((df.format(freezeHadSum / 100))
							.toString());
					fb.setFreezeWeiSum((df.format(freezeWeiSum / 100))
							.toString());
					String status = "", flag = "";
					if (Constance.Null2EmptyTrim(obj[5]).equals("0")) {
						status = "未启用";
					} else {
						status = "已启用";
					}
					fb.setUseStatus(status);
					if (Constance.Null2EmptyTrim(obj[6]).equals("0")) {
						flag = "未冻满";
					} else {
						flag = "已冻满";
					}
					fb.setFreezeFlag(flag);
					fb.setOldTransKey(Constance.Null2EmptyTrim(obj[7]));
					fb.setOldTransCardNo(Constance.Null2EmptyTrim(obj[8]));
					fb.setRecCrtTs(Constance.Null2EmptyTrim(obj[9]));
					fb.setRecUpdTs(Constance.Null2EmptyTrim(obj[10]));
					fb.setRemark(Constance.Null2EmptyTrim(obj[11]));
					fb.setOperator(Constance.Null2EmptyTrim(obj[12]));
					list.add(fb);
				}
				searchRsList.clear();
				searchRsList.addAll(list);
			}
			logger.info("开始导出强扣登记信息~");
			SXSSFWorkbook work = excelService.exportFreezeMcht(list);

			ByteArrayOutputStream output = new ByteArrayOutputStream();
			work.write(output);

			byte[] ba = output.toByteArray();
			excelFile = new ByteArrayInputStream(ba);
			output.flush();
			output.close();
			logger.info("导出强扣登记信息成功~");
		} catch (ServiceException e) {
			e.printStackTrace();
			logger.error(e.getMessage(), e);
			addActionError(e.getMessage());

		}

		return SUCCESS;
	}
	
	/**
	 * 批量导入初始化页面
	 * @return
	 */
	@Action(value = "startExportJsp", results = { @Result(name = "success", location = "/pages/freeze/exportFreeze.jsp")
    })	
	public String moreFreezeList()throws Exception
	{
		return SUCCESS;
	}
	/**
	 * 批量导入强扣商户
	 * @return
	 */
	@Action(value = "addFreezelist", interceptorRefs = {
			@InterceptorRef(value = "token"),
			@InterceptorRef(value = "rocDefaultStack", params = {
					"fileUpload.allowedExtensions", "xlsx",
					"fileUpload.maximumSize", "100000000" }) }, results = {
			@Result(name = "success",location = "/pages/freeze/exportFreeze.jsp"),
			@Result(name = "error", location = "/error.jsp"),
			@Result(name = "invalid.token", location = "/error.jsp")})
	public String addBlackLists()
	{
		try {
			Operators logingMerchant=(Operators)getSession().getAttribute(Constant.SESSION_LOGIN_MERCHANT);
			Map<String, Object> resultMap = freezeService.insertFreezeList(file, logingMerchant,exportFlag);
			if(resultMap.containsKey("result"))
			{	
				Object objMsg=resultMap.get("result");
				addActionMessage(String.valueOf(objMsg));
			}
		} catch (ServiceException e) {
			logger.error(e.getMessage(), e);
			addActionError("批量导入强扣失败~");
		}
		return SUCCESS;		
	}
	@Override
	protected BaseSearchCondition getSearchConditionFromSubClass()
			throws Exception {

		return searchCondition;
	}

	@Override
	protected void setSearchConditionToSubClass(
			BaseSearchCondition searchCondition) throws Exception {
		this.setSearchConditionToSubClass(searchCondition);
	}

	@Override
	protected void setSearchToConditionSession(
			BaseSearchCondition searchCondition) {
		getSession().setAttribute(SEARCH_SESSION_FREEZE_QUERY, searchCondition);
	}

	@Override
	protected BaseSearchCondition getSearchConditionFromSession() {

		return (BaseSearchCondition) getSession().getAttribute(
				SEARCH_SESSION_FREEZE_QUERY);
	}

	@Override
	protected String getInitPageSize() {

		return Constance.PAGE_MAX_SIZE + "";
	}

	public FreezingMerchantSearchCondition getSearchCondition() {
		return searchCondition;
	}

	public void setSearchCondition(
			FreezingMerchantSearchCondition searchCondition) {
		this.searchCondition = searchCondition;
	}

	public FreezeBean getFreezeBean() {
		return freezeBean;
	}

	public void setFreezeBean(FreezeBean freezeBean) {
		this.freezeBean = freezeBean;
	}

	public String getKeyStr() {
		return keyStr;
	}

	public void setKeyStr(String keyStr) {
		this.keyStr = keyStr;
	}

	public List<FreezeListBean> getFreezeList() {
		return freezeList;
	}

	public void setFreezeList(List<FreezeListBean> freezeList) {
		this.freezeList = freezeList;
	}

	public InputStream getExcelFile() {
		return excelFile;
	}

	public void setExcelFile(InputStream excelFile) {
		this.excelFile = excelFile;
	}
	
	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
	
	public String getExcelName() {
		String excelName = "强扣登记" + Constance.formateDate();

		try {
			excelName = new String(excelName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			logger.info("生成excel名称失败了！");
		}

		return excelName;
	}

	public String getExportFlag() {
		return exportFlag;
	}

	public void setExportFlag(String exportFlag) {
		this.exportFlag = exportFlag;
	}
	
}
